package com.laf.sinaweibo.androidtest;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.laf.sinaweibo.R;
import com.laf.sinaweibo.androidtest.MainService.MyBinder;

public class ServiceActivity extends Activity {
	
	private ServiceConnection conn;
	private MyBinder mService;
	private Button startButton;
	private Button stopButton;
	private Button bindButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.servicetest);
		startButton = (Button) findViewById(R.id.startService_button); 
		stopButton = (Button) findViewById(R.id.stopService_button); 
		bindButton = (Button) findViewById(R.id.bindService_button); 
		startButton.setOnClickListener(new OnClickListener());
		stopButton.setOnClickListener(new OnClickListener());
		bindButton.setOnClickListener(new OnClickListener());

	}
	
	private class OnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(ServiceActivity.this, MainService.class);
			switch (v.getId()) {
			case R.id.startService_button:
				startService(intent);
				
				break;
			case R.id.stopService_button:
				stopService(intent);
				
				break;
			case R.id.bindService_button:
				conn = new MyServiceConnection();
				boolean isBind = bindService(intent, conn, BIND_AUTO_CREATE);
				
				break;
			default:
				break;
			}
		}
	}
	
	class MyServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			
			Log.i("laf", "ServiceActivity: " + service.toString());
			mService = (MyBinder) service;
			Log.i("laf", "mService'method: " + mService.add(4, 6));
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			
			mService = null;
		}
	}
}
